﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:AccordionContainer runat=server></{0}:AccordionContainer>")]
    public class AccordionContainer : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        [Browsable(false)]
        public virtual AccordionCollection Accordions
        {
            get
            {
                if (_accordions == null) { _accordions = new AccordionCollection(this); }
                return _accordions;
            }
        }

        private AccordionCollection _accordions;
        private Panel parent;

        protected override void CreateChildControls()
        {
            parent = new Panel();
            parent.ID = this.ClientID;
            
            this.Controls.Add(parent);

            foreach (Accordion t in Accordions)
            {
                LiteralControl lt = new LiteralControl();
                lt.ID=t.ClientID+"_title";
                lt.Text="<h3><a href=\"#\">"+t.Title+"</a></h3>";
                parent.Controls.Add(lt);
                parent.Controls.Add(t);
            }

            LiteralControl script = new LiteralControl();
            script.ID = this.ClientID + "_script";
            script.Text = "<script language=\"javascript\" type=\"text/javascript\">";

            script.Text += string.Format("$(\"#{0}\").accordion(", parent.ClientID);

            script.Text += ");";
            script.Text += "</script>";
            this.Controls.Add(script);
        }

    }


    [ToolboxData("<{0}:Tab runat=server></{0}:Tab>")]
    public class Accordion : Panel
    {

        public string Title { get { object obj = ViewState["Title"]; return (obj == null ? "" : obj.ToString()); } set { ViewState["Title"] = value; } }
    }

    public class AccordionCollection : ControlCollection
    {
        public AccordionCollection(Control owner)
            : base(owner)
        {
        }

        public new Accordion this[int index] { get { return base[index] as Accordion; } }

        public override void Add(Control child)
        {
            base.Add((Accordion)child);
        }

        public override void AddAt(int index, Control child)
        {
            base.AddAt(index, (Accordion)child);
        }
    }
}
